<script setup lang="ts">
import type { File, TableItem, TableHeader } from '@/types/fs';

const tableHeaders: TableHeader[] = [
  { title: '文档名称', key: 'filename' },
  { title: '修改时间', key: 'modifiedAt' },
  { title: '大小', key: 'size' }
];

const usePath = () => {
  const route = useRoute();

  const path = computed(() =>
    [''].concat(route.params.slug ? (route.params.slug as string[]) : [])
  );

  return { path };
};

const { path } = usePath();
const breadcrumbsItems = computed(() => {
  const items = path.value.map((v, i) => ({
    title: v ? v : '/',
    disabled: false,
    to: `/fs${path.value.slice(0, i + 1).join('/')}`
  }));
  return items;
});

const fetchTableItems = async () => {
  const { data } = await useFetch(
    `http://10.212.67.8:2890/read_dir${path.value.join('/')}`
  );

  console.log(data.value);
  tableItems.value = (data.value as File[]).map((v) => ({
    filename: v.filename,
    modifiedAt: new Date(v.modifiedAt).toISOString(),
    size: transformSize2HumanReadable(v.size),
    isDir: v.isDir
  }));
};

fetchTableItems();

const tableItems = ref([] as TableItem[]);
const selectedItems = ref([] as TableItem[]);
const search = ref('');

const dialogActive = ref(false);
const dialogPath = ref([''] as string[]);
const dialogBreadcrumbsItems = computed(() => {
  const items = dialogPath.value.map((v) => ({
    title: v ? v : '/',
    disabled: false
  }));
  return items;
});
const dialogTableData = ref([] as File[]);
const dialogTableItems = computed(() =>
  dialogTableData.value
    .filter((v) => v.isDir)
    .map((v) => ({
      filename: v.filename,
      isDir: v.isDir
    }))
);
const dialogSelectedItems = ref([] as TableItem[]);
const dialogTableHeaders: TableHeader[] = [
  { title: '文档名称', key: 'filename' }
];
const fetchDialogTableData = async () => {
  const { data } = await useFetch(
    `http://10.212.67.8:2890/read_dir${dialogPath.value.join('/')}`
  );
  dialogTableData.value = data.value as File[];
};
const enterDir = (dir: string) => {
  dialogPath.value.push(dir);
  fetchDialogTableData();
};
const initDialog = () => {
  dialogPath.value = [''];
  fetchDialogTableData();
};
const goback = () => {
  dialogPath.value.pop();
  fetchDialogTableData();
};
const download = () => {
  const downloadFiles = selectedItems.value.filter((v) => !v.isDir);
  downloadFiles.forEach((v) => {
    const a = document.createElement('a');
    a.href = `http://10.212.67.8:2890/download${path.value.join('/')}/${v.filename}`;
    a.download = v.filename;
    a.click();
  });
};
const moveFile = async () => {
  const moveFiles = selectedItems.value.filter((v) => !v.isDir);
  const targetPath = computed(() => {
    if (dialogSelectedItems.value.length === 1) {
      return dialogPath.value
        .join('/')
        .concat('/', dialogSelectedItems.value[0].filename);
    } else {
      return dialogPath.value.join('/');
    }
  });
  const src = path.value.join('/').concat('/', moveFiles[0].filename);
  await useFetch(`http://10.212.67.8:2890/move`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: {
      src: src,
      dst: targetPath
    }
  })
    .then(() => {
      moveSuccessSnackbar.value = true;
      selectedItems.value = [];
    })
    .catch((e) => {
      alert('文件移动失败');
      console.error(e);
    })
    .finally(() => {
      fetchTableItems();
      dialogActive.value = false;
    });
};
const moveSuccessSnackbar = ref(false);

const createDirDialogActive = ref(false);
const createDirName = ref('');
const createDir = async () => {
  await useFetch(`http://10.212.67.8:2890/create${path.value.join('/')}`, {
    method: 'POST',
    body: {
      filename: createDirName.value,
      is_dir: true
    }
  }).finally(() => {
    fetchTableItems();
    createDirDialogActive.value = false;
  });
};
</script>

<template>
  <div>
    <v-row class="align-center" justify="start" no-gutters>
      <div v-if="path.length > 1">
        <NuxtLink :to="`/fs${path.slice(0, -1).join('/')}`">
          <v-icon icon="mdi-arrow-up" />
        </NuxtLink>
      </div>

      <div v-else>
        <v-icon color="grey" icon="mdi-arrow-up" />
      </div>

      <v-breadcrumbs :items="breadcrumbsItems">
        <template #divider>
          <v-icon icon="mdi-chevron-right" />
        </template>

        <template #title="{ item }">
          <NuxtLink :to="item.href">{{ item.title }}</NuxtLink>
        </template>
      </v-breadcrumbs>
    </v-row>
    <ClientOnly>
      <v-row no-gutters>
        <v-col>
          <span v-if="selectedItems.length > 0">
            <v-btn class="mr-2" color="primary" @click="download()">下载</v-btn>

            <v-divider vertical />

            <v-btn
              @click="
                dialogActive = true;
                initDialog();
              "
              >移动到</v-btn
            >
          </span>
          <span v-else>
            <v-btn color="primary" @click="createDirDialogActive = true"
              >新建文件夹</v-btn
            >
          </span>
          <v-dialog v-model="createDirDialogActive" max-width="500">
            <v-card rounded="lg">
              <v-card-text>
                <v-text-field
                  v-model="createDirName"
                  density="compact"
                  label="输入文件夹名称"
                  variant="solo-filled"
                  flat
                  hide-details
                  single-line
                />
              </v-card-text>
              <v-card-action class="d-flex justify-end">
                <v-btn color="primary mr-2" text="确认" @click="createDir()" />
                <v-btn
                  class="text-none mr-6 mb-4"
                  text="取消"
                  @click="createDirDialogActive = false"
                />
              </v-card-action>
            </v-card>
          </v-dialog>
          <v-dialog v-model="dialogActive" max-width="800" persistent>
            <v-card rounded="lg" min-height="600">
              <v-card-title class="d-flex justify-space-between align-center">
                <div class="ps-2">移动到</div>
                <v-btn
                  icon="mdi-close"
                  variant="text"
                  @click="dialogActive = false"
                />
              </v-card-title>

              <v-divider opacity="2" />

              <v-card-text>
                <v-row class="align-center" justify="start" no-gutters>
                  <div v-if="dialogPath.length > 1">
                    <v-icon icon="mdi-arrow-up" @click="goback()" />
                  </div>

                  <div v-else>
                    <v-icon color="grey" icon="mdi-arrow-up" />
                  </div>

                  <v-breadcrumbs :items="dialogBreadcrumbsItems">
                    <template #divider>
                      <v-icon icon="mdi-chevron-right" />
                    </template>

                    <template #title="{ item }">
                      <NuxtLink :to="item.href">{{ item.title }}</NuxtLink>
                    </template>
                  </v-breadcrumbs>
                </v-row>

                <v-data-table
                  v-model="dialogSelectedItems"
                  v-model:search="search"
                  :headers="dialogTableHeaders"
                  :items="dialogTableItems"
                  item-value="filename"
                  hide-default-footer
                  select-strategy="single"
                  show-select
                  return-object
                >
                  <!-- eslint-disable-next-line vue/valid-v-slot -->
                  <template #item.filename="{ item }">
                    <div
                      class="flex items-center"
                      @click="enterDir(item.filename)"
                    >
                      <div class="mr-2">
                        <v-icon color="blue" icon="mdi-folder" />
                      </div>
                      <span>
                        {{ item.filename }}
                      </span>
                    </div>
                  </template>
                </v-data-table>
              </v-card-text>

              <v-divider opacity="2" />

              <v-card-actions class="d-flex justify-end">
                <v-btn
                  color="primary"
                  rounded="xl"
                  text="确认"
                  @click="moveFile()"
                />
                <v-btn
                  class="text-none"
                  rounded="xl"
                  text="取消"
                  @click="dialogActive = false"
                />
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-col>

        <v-spacer />

        <v-col cols="4">
          <v-text-field
            v-model="search"
            density="compact"
            label="输入搜索关键词"
            prepend-inner-icon="mdi-magnify"
            variant="solo-filled"
            flat
            hide-details
            single-line
          />
        </v-col>
      </v-row>
    </ClientOnly>
    <v-snackbar
      v-model="moveSuccessSnackbar"
      text="文件移动成功"
      location="top"
      color="primary"
      variant="tonal"
      :timeout="2000"
    />
    <v-data-table
      v-model="selectedItems"
      v-model:search="search"
      :headers="tableHeaders"
      :items="tableItems"
      item-value="filename"
      hide-default-footer
      return-object
      show-select
    >
      <!-- eslint-disable-next-line vue/valid-v-slot -->
      <template #item.filename="{ item }">
        <div v-if="item.isDir">
          <NuxtLink :to="`/fs${path.join('/')}/${item.filename}`">
            <div class="flex items-center">
              <div class="mr-2">
                <v-icon color="blue" icon="mdi-folder" />
              </div>
              <span>
                {{ item.filename }}
              </span>
            </div>
          </NuxtLink>
        </div>

        <div v-else class="flex items-center">
          <div class="mr-2">
            <v-icon icon="mdi-file" />
          </div>
          <span>
            {{ item.filename }}
          </span>
        </div>
      </template>
    </v-data-table>
  </div>
</template>
